package com.yexin.qingzhou.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Map;

@Configuration
public class JwtUtil {

    @Value("${jwt.secret}")
    private String KEY;

    @Value("${jwt.expiration}")
    private long expiration ;

    //接收业务数据,生成token并返回
    public String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + expiration))
                .sign(Algorithm.HMAC256(KEY));
    }

    //接收token,验证token,并返回业务数据
    public Map<String, Object> parseToken(String token) {
        Map<String, Object> claims = JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
        
        // 确保id是Long类型
        Object idObj = claims.get("id");
        if (idObj instanceof Integer) {
            claims.put("id", ((Integer) idObj).longValue());
        }
        
        return claims;
    }

}
